﻿//文件指定编译编码UTF-8
#pragma execution_character_set("utf-8")
#include "disposethread.h"
#include "scanruleservice.h"

#include <qglobalconfig.h>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <Windows.h>

DisposeThread::DisposeThread(QObject *parent) : QThread(parent)
{
    moveToThread(this);
    isRun = false;
}

DisposeThread::~DisposeThread()
{
    stop();
    quit();
    wait();
}

void DisposeThread::stop()
{
    isRun = false;
}

bool fileNameContains(const QString &fileName,const QStringList &list,QString &matchName){
    for(QString item:list){
//        if(fileName.contains(item)){
//            matchName = item;
//            return true;
//        }
        if(fileName.toUpper() == item.toUpper()){
            matchName = item;
            return true;
        }
    }
    return false;
};

void DisposeThread::scanDirectory(const QString &path,const QStringList &removeNameList,const QMap<QString, QString> &replaceNameMap)
{
    QDir dir(path);
    if (!dir.exists()) {
        qDebug() << "目录不存在：" << path;
        return;
    }
    signal_workMsg(QString("【正在扫描】：%1").arg(path));

    QFileInfoList list = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);

    foreach (const QFileInfo &info, list) {
        totalFiles ++;
        if(!isRun){
            return;
        }
        if (info.isDir()) {
            scanDirectory(info.absoluteFilePath(),removeNameList,replaceNameMap);
        } else {

            QString filePath = info.absoluteFilePath();
            if(skipFilePath.contains(filePath)){
                qDebug() << "跳过待替换文件：" << filePath;
                continue;
            }
            QString matchName;
            if (fileNameContains(info.fileName(),removeNameList,matchName)) {
                qDebug() << "找到[删除]目标文件：" << filePath;
                QFile::remove(filePath);
                qDebug() << "已删除文件：" << filePath;
                removedCount ++;
            }
            if (fileNameContains(info.fileName(),replaceNameMap.keys(),matchName)) {
                qDebug() << "找到[替换]目标文件：" << filePath;
                QString replacementPath = replaceNameMap.value(matchName);
                if (!replacementPath.isEmpty()) {
                    QFile::remove(filePath);
                    QFile::copy(replacementPath, filePath);
                    qDebug() << "已用" << replacementPath << "替换文件：" << filePath;
                    replacedCount ++;
                }
            }
        }
        QThread::msleep(0);
    }
}

void DisposeThread::run()
{
    totalFiles = 0;
    removedCount = 0;
    replacedCount = 0;
    skipFilePath.clear();

    isRun = true;
    isError = false;

    signal_workStatus(true);
    signal_workMsg("扫描启动!");

    ScanRuleService scanRuleService;
    // 获取扫描规则
    QList<ScanRule> ruleList;
    if (!scanRuleService.getList(ruleList)) {
        isError = true;
        isRun = false;
        signal_workMsg("获取扫描策略列表失败!");
    }else{
        // 整理规则
        QStringList removeNameList; // 文件名匹配删除
        QMap<QString, QString> replaceNameMap; // 文件名匹配替换

        for (const ScanRule& item : qAsConst(ruleList)) {
            if (item.getDisposeMode() == 0) {
                removeNameList.append(item.getFilterName());
            }else if(item.getDisposeMode() == 1) {
                replaceNameMap.insert(item.getFilterName(),item.getReplacePath());
                skipFilePath.append(item.getReplacePath());
            }
        }
        // 读取配置参数
        QString scanDir = QGlobalConfig::getInstance().read("param", "scanDir", "").toString();        // 要扫描的目录
        if(scanDir.isEmpty()){
            // 获取所有盘符扫描
            QFileInfoList drives = QDir::drives();
            for(const QFileInfo &info:drives){
                scanDirectory(info.filePath(),removeNameList,replaceNameMap);
                if(!isRun){
                    break;
                }
            }
        }else{
            scanDirectory(scanDir,removeNameList,replaceNameMap);
        }
    }

    signal_workStatus(false);
    if (!isError) {
        QString msg = QString("扫描停止！共处理 %1 个文件，成功删除 %2 个，成功升级：%3 个）")
                .arg(totalFiles).arg(removedCount)
                .arg(replacedCount);
        signal_workMsg(msg);
    } else {
        signal_workMsg("扫描异常终止！");
    }
}
